import axios from 'axios';
import qs from 'qs';
import Vue from 'vue';


// 拦截器
axios.interceptors.request.use(config => {
    return config;
}, error => {
    return Promise.reject(error);
});
axios.interceptors.response.use(response => {
    return response;
}, error => {
    if (error && error.response) {
        if (error.response.status === 504) {
            Vue.prototype.$message({type: 'error', duration: 1000, message: '网络超时', center: true});
        }
        if (error.response.status === 404) {
            Vue.prototype.$message({type: 'error', duration: 1000, message: '请求出错', center: true});
        }
        //token失效
        if (error.response.status === 401){
            Vue.prototype.vueVm.$router.push('/login');
        }
        if(error.response.status === 403){
            Vue.prototype.vueVm.$router.push('/403');
        }
    }
    return Promise.resolve(error.response);
});
// 函数定义
export default function axiosHttpUtil(opts, data) {
    // valid params is null有
    if (!opts.method || !opts.url) {
        return false;
    }
    if (data && opts.method === 'get') {
        data.ver = new Date().getTime();
    }
    //公共参数
    let Public = {},
        token = sessionStorage.getItem('token') !== 'null' ? JSON.stringify(opts.header).substring(0, JSON.stringify(opts.header).length - 1) + ',"token":' + '"' + sessionStorage.getItem('token') + '"}' : JSON.stringify(opts.header),
        defaultHeader = JSON.parse(token) ? JSON.parse(token) : opts.method === 'get' ? {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json', 'Content-Type': 'application/json; charset=UTF-8', 'CCache-control': 'no-cache', 'Pragma': 'no-cache', 'Cache': 'no-cache'} : {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json;charset=UTF-8'},
        paramsTest = defaultHeader && defaultHeader['Content-Type'] === 'application/x-www-form-urlencoded' ? qs.stringify(data) : data,
        //http默认配置
        httpDefaultOpts = {
            baseURL: '../',
            method: opts.method,
            url: opts.url,
            // + '?t=' + new Date().getTime(),
            timeout: 1000 * 60 * 2,
            params: Object.assign(Public, data),
            headers: defaultHeader,
            data: paramsTest
        };

    if (opts.method === 'get') {
        delete httpDefaultOpts.data;
    } else {
        delete httpDefaultOpts.params;
    }
    return new Promise((resolve, reject) => {
        axios(httpDefaultOpts).then((res) => {
            if (res) {
                resolve(res);
            } else {
                resolve({data: {message: '服务器连接异常'}});
            }
        }
        ).catch((res) => {
            reject(res);
        });
    });
}
